/**
 * 作者：陈文斌 on 2019/1/19.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:crm/constant/constant.dart';

final TextStyle _availableStyle = TextStyle(
  color: Colors.white,
  fontSize: AppFontSizes.Font12,
  fontFamily: AppFontFamilies.PingFangSC,
  fontWeight: FontWeight.w500,
);

final TextStyle _unavailableStyle = TextStyle(
  color: AppColors.PlaceholderTextColor,
  fontSize: AppFontSizes.Font12,
  fontFamily: AppFontFamilies.PingFangSC,
  fontWeight: FontWeight.w500,
);

class LoginFormCode extends StatefulWidget {
  /// 倒计时的秒数，默认60秒。
  final int countdown;

  /// 用户点击时的回调函数。
  final VoidCallback onTap;

  @override
  LoginFormCode({
    this.countdown = 60,
    this.onTap,
  });

  State<StatefulWidget> createState() {
    return _LoginFormCodeState();
  }
}

class _LoginFormCodeState extends State<LoginFormCode> {
  /// 倒计时的计时器。
  Timer _timer;

  /// 当前倒计时的秒数。
  int _seconds;

  TextStyle inkWellStyle = _availableStyle;

  String _verifyStr = '获取验证码';

  bool _available = true;

  @override
  void initState() {
    super.initState();
    _seconds = widget.countdown;
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      print(_seconds);
      if (_seconds == 0) {
        _cancelTimer();
        _seconds = widget.countdown;
        inkWellStyle = _availableStyle;
        setState(() {});
        return;
      }
      _seconds--;
      _verifyStr = '已发送($_seconds)';
      inkWellStyle = _unavailableStyle;
      if (_seconds == 0) {
        _verifyStr = '重新发送';
      }
      setState(() {});
    });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    Widget _button(String verifyStr, TextStyle inkWellStyle) {
      return Container(
        height: 24,
        constraints: BoxConstraints(minWidth: 90),
        decoration: BoxDecoration(
          color: AppColors.MainColor,
          borderRadius: BorderRadius.circular(4),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: MaterialButton(
            onPressed: () {
              if (_available) {
                _startTimer();
                inkWellStyle = _unavailableStyle;
                _available = false;
                if (widget.onTap != null) {
                  widget.onTap();
                }
              }
            },
            padding: EdgeInsets.all(0),
            child: Text(
              verifyStr,
              style: inkWellStyle,
            ),
          ),
        ),
      );
    }

    return _available
        ? _button('获取验证码', _availableStyle)
        : _button(_verifyStr, inkWellStyle);
  }
}
